package com.isljj.web_chat2.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.isljj.web_chat2.config.OnlineUserManager;
import com.isljj.web_chat2.mapper.MessageMapper;
import com.isljj.web_chat2.mapper.SessionMapper;
import com.isljj.web_chat2.model.*;
import com.isljj.web_chat2.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@Controller
@Slf4j
public class WebsocketController extends TextWebSocketHandler {
    @Autowired
    JWTUtils jwtUtils;
    @Autowired
    OnlineUserManager onlineUserManager;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    SessionMapper sessionMapper;
    @Autowired
    MessageMapper messageMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //log.info("webSocketController 连接成功");
        String token = (String) session.getAttributes().get("token");
        User user = jwtUtils.getUserByToken(token);
        //log.info("登录用户 userId = " + user.getUserId());
        boolean flag = onlineUserManager.online(user.getUserId(),session);
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        super.handleBinaryMessage(session, message);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws JsonProcessingException {

        log.info("收到消息 - " + message.getPayload().toString());
//
        String token = (String) session.getAttributes().get("token");
        User user = jwtUtils.getUserByToken(token);
        String messagString =  message.getPayload().toString();
        WSMessageRequest WSMessageRequest = objectMapper.readValue(messagString, WSMessageRequest.class);
//        转发给服务器
        transpondMessage(user, WSMessageRequest);
    }

//    转发工作
    private void transpondMessage(User fromUser, WSMessageRequest WSMessageRequest) throws JsonProcessingException {
//        构造一个返回信息

        try {
            new URL(WSMessageRequest.getContent());
            WSMessageRequest.setContent(WSMessageRequest.getContent().replaceAll("AI×",""));
        } catch (MalformedURLException e) {

        }

        WSMessageResponse WSMessageResponse = new WSMessageResponse();
        WSMessageResponse.setFromId(fromUser.getUserId());
        WSMessageResponse.setFromName(fromUser.getUserName());
        WSMessageResponse.setSessionId(WSMessageRequest.getSessionId());
        WSMessageResponse.setContent(WSMessageRequest.getContent());
        //        当前是java对象,----->json字符串
        String respJson = objectMapper.writeValueAsString(WSMessageResponse);
//        先查要发给谁
        List<Friend> userList = sessionMapper
                .selectSessionFriends(WSMessageRequest.getSessionId(),fromUser.getUserId());
        Friend friend = new Friend();
        friend.setFriendId(fromUser.getUserId());
        friend.setFriendName(fromUser.getUserName());
        userList.add(friend);//把自己添加上
//        遍历发送 发给服务器
        for(Friend toUser:userList){
//            获取session
            try {
                onlineUserManager.getSession(toUser.getFriendId())
                        .sendMessage(new TextMessage(respJson));
            } catch (NullPointerException e) {
                continue;
            } catch (IOException e) {
                continue;
            }
        }
//        数据持久化保存
//        构造一个message
        Message message = new Message();

        message.setFromId(fromUser.getUserId());
        message.setSessionId(WSMessageRequest.getSessionId());
        message.setContent(WSMessageRequest.getContent());
        //判断是否为url

        messageMapper.insertMessage(message);
//        更新会话时间
        sessionMapper.updateDate(WSMessageRequest.getSessionId());

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info(exception.toString());
        log.info("webSocketController 连接异常");
        String token = (String) session.getAttributes().get("token");
        User user = jwtUtils.getUserByToken(token);
        onlineUserManager.offline(user.getUserId(),session);
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("webSocketController 连接断开");
        String token = (String) session.getAttributes().get("token");
        User user = jwtUtils.getUserByToken(token);
        onlineUserManager.offline(user.getUserId(),session);
    }
}
